package com.Classroom.al.controllers;

import com.Classroom.al.dao.ClassroomRepository;
import com.Classroom.al.dao.StudentRepository;
import com.Classroom.al.dto.ChartData;
import com.Classroom.al.dto.StudentClassroom;
import com.Classroom.al.entities.Classroom;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class HomeController {
    @Value("${version}")
    private String version;

    @Autowired
    ClassroomRepository classroomRepository;
    @Autowired
    StudentRepository studentRepository;
    @GetMapping("/")
    public String displayHome(Model model) throws JsonProcessingException {

        model.addAttribute("versionNumber",version);
        List<Classroom> classrooms =classroomRepository.findAll();
        model.addAttribute("classrooms",classrooms);

        List<ChartData> classroomStatusData = classroomRepository.getClassroomsStatus();
        if (Objects.isNull(classroomStatusData)){
            classroomStatusData=new ArrayList<ChartData>(0);
        }
        ObjectMapper objectMapper =new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(classroomStatusData);
//        String jsonString = JSON.toJSONString(classroomStatusData);

        model.addAttribute("classroomStatusData",jsonString);

        List<StudentClassroom> studentClassrooms = studentRepository.studentClassrooms();
        model.addAttribute("studentClassrooms",studentClassrooms);

        return "main/home";

    }
}
